﻿using AutoMapper;
using MediatR;
using SmartProduction.Domain.ProductionOrders;
using SmartProduction.ErrorCode;
using SmartProduction.Infarstructrue.Interface;
using SmartProduction.Read.API.Application.Commands.ItemListInfoCommand;

namespace SmartProduction.Read.API.Application.CommandHandlers.ItemListInfoCommandHandler
{
    /// <summary>
    /// 物品列表命令处理方法
    /// </summary>
    public class ItemListInfoQueryCommandHandler : IRequestHandler<ItemListInfoQueryCommand, APIPaing<List<ItemListInfo>>>
    {
        /// <summary>
        /// AutoMapper
        /// </summary>
        private readonly IMapper mapper;
        /// <summary>
        /// 物品列表
        /// </summary>
        private readonly IBaseRepository<ItemListInfo> itemListRepository;
        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="itemListRepository"></param>
        public ItemListInfoQueryCommandHandler(IMapper mapper, IBaseRepository<ItemListInfo> itemListRepository)
        {
            this.mapper = mapper;
            this.itemListRepository = itemListRepository;
        }
        /// <summary>
        /// 物品列表命令处理
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<APIPaing<List<ItemListInfo>>> Handle(ItemListInfoQueryCommand request, CancellationToken cancellationToken)
        {
            APIPaing<List<ItemListInfo>> result = new APIPaing<List<ItemListInfo>>();
            var list = itemListRepository.GetAll().Result;
            result.TotalCount = list.Count();
            result.PageCount = (int)Math.Ceiling((double)result.TotalCount / request.PageSize);
            list = list.OrderByDescending(o => o.ItemListId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);
            var data = mapper.Map<List<ItemListInfo>>(list);
            result.Code = APIEnums.查询成功;
            result.Msg = APIEnums.查询成功.ToString();
            result.data = data;
            return await Task.FromResult(result);
        }
    }
}
